package com.wangyadong.hobby.schedule.jobtask.dsa.lesson1;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2019/1/916:25
 **/
public class CaesarCipher {

    protected char[] encoder = new char[26];
    protected char[] decoder = new char[26];

    public CaesarCipher(int rotation) {
        for (int k = 0; k < 26; k++) {
            encoder[k] = (char) ('A' + (k + rotation) % 26);
            decoder[k] = (char) ('A' + (k - rotation + 26) % 26);
        }
    }

    public String encrypt(String message) {
        return transform(message, encoder);
    }

    public String decrypy(String secret) {
        return transform(secret, decoder);
    }

    private String transform(String original, char[] code) {
        char[] msg = original.toCharArray();
        for (int k = 0; k < msg.length; k++) {
            if (Character.isUpperCase(msg[k])) {
                int j = msg[k] - 'A';
                msg[k] = code[j];
            }
        }
        return new String(msg);
    }

    public static void main(String[] args) {
        CaesarCipher caesarCipher = new CaesarCipher(20);
        System.out.println("Entryption code =" + new String(caesarCipher.encoder));
        System.out.println("Detryption code =" + new String(caesarCipher.decoder));
        String message = "THE EAGLE IS IN PLAY; MEET AT JOE'S";
        String code = caesarCipher.encrypt(message);
        System.out.println("Secret: " + code);
        String answer = caesarCipher.decrypy(code);
        System.out.println("Message :" + answer);
    }

}
